<?php
// 用于前台展示的基类
class FrontAction extends GlobalAction {

	/**
	 * 初始化函数
	 * @author 姜伟
	 * @param void
	 * @return void
	 * @todo 调用父类初始化方法，控制前台的页面展示，COOKIE值设置，公用链接等
	 */
	function _initialize()
	{
		#dump($_SERVER['HTTP_USER_AGENT']);die;
		// session('user_id',null);
#session('user_address_id', null);
#session('area_id', null);
#die;
// session('user_id', 62146);
#session('user_id', null); die;

		parent::_initialize();
		$footer_path = APP_PATH . '/Tpl/footer.html';
		/*if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger'))
		{*/
			$base_path = dirname($this->_get_template_file('mall_home'));
#$this->assign('base_path', $base_path);
			$this->assign('header_path', $base_path ? $base_path . '/header.html' : '../header.html');
			$footer_path = $base_path ? $base_path . '/footer.html' : '../footer.html';
			$tpl_path = dirname($this->_get_template_rel_file('mall_home'));
			$this->assign('tpl_path', $tpl_path);
		//}
		$this->assign('footer_path', $footer_path);
#echo MODULE_NAME . '/' . ACTION_NAME;
		#echo 'aa';
		#die;
		//过滤PC端访问
		if (strpos(strtolower(ACTION_NAME), 'response'))
		{
			return;
		}
		//session有效时间设置
        ini_set('session.gc_maxlifetime', 999999);

		//获取用户信息
		$user_id = intval(session('user_id'));
		if($user_id){
			$is_enable = M('Users')->where('user_id ='.$user_id)->getField('is_enable');
			if($is_enable == 2){
				session('user_id', null);
			}
		}

		if (!$user_id && strtoupper(PHP_OS) != 'LINUX')
		{
			//session('user_id', 39454);
		}

		if (!$user_id && strtoupper(PHP_OS) == 'LINUX')
		{
			#$this->get_weixin_user_info();
			if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger'))
			{
				//微信用户获取用户ID
				//session('user_id', 39454);
				#$this->get_weixin_user_info();
			}
			else
			{
				//非微信用户获取用户ID
				#$this->get_user_info();
			}
			$this->assign('first', 'yes');
		}
		else
		{
			$user_obj = new UserModel();
			$user_info = $user_obj->getUserInfo('user_id', 'user_id = ' . $user_id);
		}

		//是否ios
		if(strpos($_SERVER['HTTP_USER_AGENT'], 'iPhone') || strpos($_SERVER['HTTP_USER_AGENT'], 'iPod') || strpos($_SERVER['HTTP_USER_AGENT'], 'iPad')){
			$this->assign('isios', 1);
		}else{
			$this->assign('isios', 0);
		}
		#dump($_SERVER['HTTP_USER_AGENT']);die;

		//是否有未读消息
		$message_num = D('Message')->getMessageNum('reply_user_id ='.intval(session('user_id')) .' and is_read = 0');

		// $sx_num = M('Users')->where('user_id ='.$user_id)->getField('sx_num');
		$this->assign('is_read', $message_num ? true : false);

		$this->assign('is_login', session('user_id') ? 1 : 0);


		//查找未采纳答案并且超时的悬赏，平分悬赏金
		// D('Reward')->noAdoptAvgRewardMoney();
		// $this->cf_end();

		$this->assign('ios_recharge', json_encode(AccountModel::iosRecharge(), JSON_UNESCAPED_UNICODE));

        $is_hidden = 0;
        if(strpos($_SERVER['HTTP_USER_AGENT'], 'iPhone') || strpos($_SERVER['HTTP_USER_AGENT'], 'iPod') || strpos($_SERVER['HTTP_USER_AGENT'], 'iPad')){
            //ios
            if($_SERVER['HTTP_WEBVERSION']){
                $ios_version = $_SERVER['HTTP_WEBVERSION'];
                session('ios_web_version',$_SERVER['HTTP_WEBVERSION']);
            }else{
                $ios_version = session('ios_web_version');
            }
            $acp_ios_version = $GLOBALS['config_info']['IOS_VERSION'];
            if($ios_version > $acp_ios_version){
                $is_hidden = 1;
            }
        }else{
            //android
            if($_SERVER['HTTP_USER_AGENT']){
                $web_version = $_SERVER['HTTP_USER_AGENT'];
                log_file('HTTP_USER_AGENT ='.json_encode($web_version),'ccy_debug');

                $pattern = '/VERSION_CODE\:([^\s]+)/i';
                preg_match($pattern, $web_version, $matches);

                log_file('matches ='.json_encode($matches),'ccy_debug');

                $web_version = $matches[1];
                session('web_version',$web_version);
            }else{
                $web_version = session('web_version');
            }
            $acp_web_version = $GLOBALS['config_info']['WEB_VERSION'];
            if($web_version > $acp_web_version){
                $is_hidden = 1;
            }
        }

        $this->is_hidden = $is_hidden;
        $this->assign('is_hidden',$is_hidden);

        log_file('ios_version ='.$ios_version,'ccy_debug');
        log_file('web_version ='.$web_version,'ccy_debug');
        log_file('version ='.json_encode($_SERVER),'ccy_debug');

		/*** 链接传值begin ***/
		//首页 XX
		$this->assign('home_link', U('/'));


		//他人个人中心主页
		$this->assign('others_personal_center_link','/Index/others_personal_center');
		//他的关注页面
		$this->assign('his_concern_link','/Index/his_concern');
		//他的粉丝页面
		$this->assign('his_fans_link','/Index/his_fans');
		//他的关注频道页面
		$this->assign('his_concernChannel_link','/Index/his_concernChannel');
		//我的关注页面
		$this->assign('my_concern_link','/Index/my_concern');
		//我的粉丝页面
		$this->assign('my_fans_link','/Index/my_fans');
		//我参与的悬赏
	    $this->assign('my_joined_reward_link','/Index/my_joined_reward');
	    //我赞赏的
	    $this->assign('my_appreciated_link','/Index/my_appreciated');
	    //我的心愿
	    $this->assign('my_Crowd_funding_link','/Index/my_Crowd_funding');
	    //我的浏览记录
	    $this->assign('my_scan_record_link','/Index/my_scan_record');
	    //我的赞赏帖子
	    $this->assign('my_post_link','/Index/my_post_zanshang');
	    //我的悬赏帖子
	    $this->assign('my_post_link','/Index/my_post_xuanshang');
	    //我的心愿帖子
	    $this->assign('my_post_link','/Index/my_post_zhongchou');
	    //我的普通帖子
	    $this->assign('my_post_link','/Index/my_post_common');
	    //我的收藏
	    $this->assign('my_collection_link','/Index/my_collection');
	    //我的钱包
    	$this->assign('my_wallet_link','/Index/my_wallet');	
    	//余额充值
    	$this->assign('recharge_link','/Index/recharge');	
    	//提现
    	$this->assign('withdraw_link','/Index/withdraw');
    	//设置提现账户
    	$this->assign('set_withdraw_account_link','Index/set_withdraw_account');
    	//输入提现账户
    	$this->assign('input_withdraw_account_link','Index/input_withdraw_account');
    	//小额免密支付
    	$this->assign('no_psw_pay_link','Index/no_psw_pay');
    	//消费记录-支出
    	$this->assign('consume_record_expenditrue_link','Index/consume_record_expenditrue');
    	//消费记录-收入
    	$this->assign('consume_record_income_link','Index/consume_record_income');

    	//消费记录-充值
    	$this->assign('consume_record_recharge_link','Index/consume_record_recharge');
    	//我的消费记录
    	$this->assign('my_consume_record_link','Index/my_consume_record');
    	//消费记录-提现
    	$this->assign('consume_record_withdraw_link','Index/consume_record_withdraw');
    	//我的个人中心
    	$this->assign('my_personal_center_link','Index/my_personal_center');
    	//关于我们
    	$this->assign('aboutus_link','Index/aboutus');
    	//头衔首页
    	$this->assign('title_index_link','Index/title_index');
    	//领取
    	$this->assign('get_title_link','Index/get_title');
    	//我的资料
    	$this->assign('my_data_link','Index/my_data');
    	//系统设置
    	$this->assign('system_set_link','Index/system_set');
    	//账号安全
    	$this->assign('account_safe_link','Index/account_safe');
    	//修改账号密码
    	$this->assign('modify_account_psw_link','Index/modify_account_psw');
    	//设置支付密码
    	$this->assign('set_pay_psw_link','Index/set_pay_psw');
    	//确认支付密码
    	$this->assign('confirm_pay_psw_link','Index/confirm_pay_psw');
    	//修改支付密码
    	$this->assign('modify_pay_psw_link','Index/modify_pay_psw');
    	//修改支付密码成功
    	$this->assign('set_success_pay_psw_link','Index/set_success_pay_psw');
    	//忘记支付密码
    	$this->assign('forget_pay_psw_link','Index/forget_pay_psw');
    	//隐私设置
    	$this->assign('privacy_set_link','Index/privacy_set');
    	//视频
    	$this->assign('live_link','Index/live');
    	//视频频道
    	$this->assign('live_channel_link','Index/live_channel');
    	//申请特殊头衔
    	$this->assign('apply_special_title_link','Index/apply_special_title');
    	//意见反馈
    	$this->assign('feedback_link','Index/apply_special_title');

		//生成二维码

		get_qr_code();

		//if(strtoupper(PHP_OS)!="LINUX")
		/*$user_id = intval(session('user_id'));
		if (!$user_id)
		{
			session('user_id', 6892);
			$user_id = 6892;
			//测试，上线后删除
			#$user_address_id = $user_address_id ? $user_address_id : 41;
			#session('user_address_id', $user_address_id);
		}*/

		//是否关注微信号，没有则跳转到扫码页面
		$user_id = intval(session('user_id'));
		$user_obj = new UserModel($user_id);
		$user_info = $user_obj->getUserInfo('subscribe, openid');
		if (!$user_info['openid']) {
			//$this->get_weixin_user_info();
		}

		if (strtoupper(PHP_OS) == 'LINUX' && intval($user_info['subscribe']) != 1  && ACTION_NAME != 'show_qr_code') 
		{
			//调用微信查看是否关注
			$appid = C('APPID');
			$secret = C('APPSECRET');
			Vendor('Wxin.WeiXin');
			$token_id = WxApi::getAccessToken($appid, $secret);
			$wx_obj = new WxApi($token_id);
			$user_info_wx = $wx_obj->user_info($user_info['openid']);
			if ($user_info_wx['subscribe'] == 1) {
				//已关注修改数据库中的值
				$user_obj->editUserInfo(array('subscribe' => 1));
			} else {
				#redirect('/FrontUser/show_qr_code');
			}
		}


		//是否app打开
		log_file('user_agent='.json_encode($_SERVER), 'user_agent');
	
		//获取分享代码
		Vendor('jssdk');
		$jssdk = new JSSDK(C("APPID"), C("APPSECRET"));
		$signPackage = $jssdk->getSignPackage(); 
		// dump($signPackage);die;
		$this->signPackage = $signPackage;
		$this->assign('signPackage', $signPackage);

		//用户头像
		$user_obj = new UserModel($user_id);
		$user_info = $user_obj->getUserInfo('headimgurl');
		$item_info['pic'] = $user_info['headimgurl'];
		$pic = $pic ?  'http://' . $_SERVER['HTTP_HOST'] . $pic : $item_info['pic'];
		$share_info['pic'] = $pic;
		$this->assign('share_info', $share_info);
		$wx_share_link = get_url() . '?rec_user_id=' . $user_id;
		$this->assign('wx_share_link', $wx_share_link);
		log_file('user_id = ' . $user_id . ', action_name = ' . ACTION_NAME . ', share_info = ' . json_encode($share_info), 'share');
		#log_file(json_encode($signPackage), 'share');

		log_file('wx_share_link = ' . $wx_share_link, 'detail');
		log_file(json_encode($signPackage), 'detail');

		//传值到前台
		$user_id = intval(session('user_id'));
		$this->assign('user_id', $user_id ? $user_id : 0);
		$this->assign('client_ip', get_client_ip());	
		//是否app，根据agent中是否包含b2cyr判断
		$is_app = strpos($_SERVER['HTTP_USER_AGENT'], 'yrb2c') ? 1 : 0;
		log_file($is_app, 'cc', true);
		$this->assign('is_app', $is_app);

		//是否开启免密支付
        $user = D('User')->getUserInfo('npw_pay', 'user_id ='.$user_id);
        $this->assign('npw_pay', $user['npw_pay']);
	}

	/**
	 * 根据COOKIE获取用户信息，判断是否会员，若是，写session后退出；否则为之注册
	 * @author 姜伟
	 * @param void
	 * @return user_id
	 * @todo 
	 */
	function get_user_info()
	{
		//要过滤的user_agent
		$agent_arr = array(
			'Baiduspider',	//百度
			'Googlebot',	//谷歌
			'iaskspider',	//新浪
			'Sogou',	//搜狗
			'YodaoBot',	//网易有道
			'msnbot',	//微软msn
			'bot',	//所有
			'Bot',	//所有
			'spider',//所有
			'Spider',//所有
			'AppleWebKit',//所有
			'Alibaba.Security.Heimdall',
			'Gecko/20100101',
		);
		foreach ($agent_arr AS $k => $v)
		{
			if (strpos($_SERVER['HTTP_USER_AGENT'], $v))
			{
				log_file('爬虫' . $v, 'spider');
				return;
			}
		}
		$user_obj = new UserModel();
		$user_info = $user_obj->getUserInfo('user_id', 'role_type = 3 AND user_cookie = "' . $GLOBALS['user_cookie'] . '"');
		if ($user_info)
		{
			//用户存在，设置session
			session('user_id', $user_info['user_id']);
		}
		else
		{
			//用户不存在，为之注册
			$arr = array(
				'user_cookie'           => $GLOBALS['user_cookie'],
				'role_type'             => 3,
				'is_enable'             => 1,
				'reg_time'              => time(),
			);
			$user_id = $user_obj->addUser($arr);
			$member_obj = new MemberModel();
			$arr = array(
				'member_id'	=> $user_id
			);
			$member_obj->addMember($arr);
log_file('user_agent = ' . $_SERVER['HTTP_USER_AGENT'], 'user');
			session('user_id', $user_id);
		}
	}

	/**
	 * 获取微信用户信息，判断是否会员，若是，写session后退出；否则为之注册
	 * @author 姜伟
	 * @param void
	 * @return user_id
	 * @todo 
	 */
	function get_weixin_user_info()
	{
		$appid = C('APPID');
		$secret = C('APPSECRET');

		if (!isset($_GET['code']))
		{
			$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
log_file($redirect_uri);
			//获取授权码的接口地址
			$url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . $appid . '&redirect_uri=' . urlencode($redirect_uri) .'&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect';
			$user_model = M('users');
			$user_info = $user_model->field('user_id, role_type, openid, nickname, sex, headimgurl, access_token, refresh_token, token_expires_time')->where('user_cookie = "' . $GLOBALS['user_cookie']. '"')->find();
			if (!$user_info)
			{
				redirect($url);
			}

			//访问令牌过期
			if ($user_info['token_expires_time'] < time())
			{
				//刷新令牌存在，用之交换访问令牌
				if ($user_info['refresh_token'])
				{
					$url = 'https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=' . $appid . '&grant_type=refresh_token&refresh_token=' . $user_info['refresh_token'];
					Vendor('Wxin.WeiXin');
					$wx_obj = new WeiXinUser($appid, $secret);
					$wx_obj->getAccessToken($url);
				}
				else
				{
					redirect($url);
				}
			}
			else
			{
				session('user_id', $user_info['user_id']);
				session('planter_id', $user_info['current_planter_id']);
			}
		}
		else
		{
			$rec_user_id = $_GET['rec_user_id'];
			$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . $appid . "&secret=" . $secret . "&code=" . $_GET['code'] .  "&grant_type=authorization_code";
			Vendor('Wxin.WeiXin');
			$wx_obj = new WeiXinUser($appid, $secret, $this->parentId);
			$wx_obj->getAccessToken($url, $rec_user_id);
		}
	}

	/**
	 * 404页面
	 * @author 姜伟
	 * @param void
	 * @return void
	 * @todo 输出404页面信息
	 */
	public function page_not_found()
	{
		$this->display();
	}

	/**
	 * 支付宝付款成功后的异步回调处理
	 * @author 姜伟
	 * @param void
	 * @return void
	 * @todo 调用支付宝支付模型验证来源可靠性后，获取订单号，调用订单模型的payOrder方法设置订单状态为已付款
	 */
	public function alipay_response()
	{
		//通知记录
		$file = fopen('Logs/alipay_response_log.txt', 'a');
		fwrite($file, date('Y-m-d H:i:s', time()) . "\t" . (isset($_POST['out_trade_no']) ? $_POST['out_trade_no'] : 'invalid visit') . "\n");
		fclose($file);

		$alipay_obj = new AlipayModel();
		$success = $alipay_obj->pay_response();
		if ($success)
		{
			echo 'success';
		}
	}

	public function mobile_alipay_response_post()
	{
		//通知记录
		$file = fopen('Logs/mobile_alipay_response_log.txt', 'a');
		fwrite($file, date('Y-m-d H:i:s', time()) . "\t" . (isset($_POST['out_trade_no']) ? $_POST['out_trade_no'] : 'invalid visit') . "\n");
		fclose($file);

		$alipay_obj = new AlipayModel();
		$success = $alipay_obj->mobile_pay_response();
		if ($success)
		{
			echo 'success';
		}
	}
	
	

	/**
	 * 支付宝付款成功后的异步回调处理
	 * @author zt
	 * @param void
	 * @return void
	 * @todo 调用支付宝支付模型验证来源可靠性后，获取订单号，调用订单模型的payOrder方法设置订单状态为已付款
	 */
	public function alipay_response_post()
	{
		//通知记录
		#$file = fopen('Logs/alipay_response_log.txt', 'a');
		$file = fopen('logs/alipay_response_log.' . date('Y-m-d', time()) . '.txt', 'a');
		fwrite($file, date('Y-m-d H:i:s', time()) . "\t" . (isset($_POST['out_trade_no']) ? $_POST['out_trade_no'] : 'invalid visit') . "\n");
		fclose($file);
	
		$alipay_obj = new AlipayModel();
		$return_state = $alipay_obj->pay_response_post();
		if ($return_state == 2)
		{
			$total_fee = $_POST['total_fee'];	//充值的总额
			require_once('Common/func_sms.php');
			$sms_total = sms_recharge($total_fee);	//为客户充值的金额
				
			//短信充值日志的记录
			$account = new AccountModel();
			$account->addSMSPayLog($_POST['out_trade_no'],1,$total_fee,$sms_total);
				
			$this->success('恭喜您，充值成功', '/AcpConfig/sms_config/mod_id/0');
		}
		else
		{
			$this->error('对不起，非法访问', U('/'));
		}
	}
	
	/**
	 * 微信付款成功后的异步回调处理
	 * @author zt
	 * @param void
	 * @return void
	 * @todo 调用微信支付模型验证来源可靠性后，获取订单号，调用订单模型的payOrder方法设置订单状态为已付款
	 */
	public function wxpay_response()
	{
		//通知记录
		#$file = fopen('logs/weixin_response_log.' . date('Y-m-d', time()) . '.txt', 'a');
		#$str = '';
		#foreach($_REQUEST as $key => $val)
		#{
			#$str .= "&$key=$val";
		#}
		#fwrite($file, date('Y-m-d H:i:s', time()) . "\t" . 'post str: ' . $str . "\n");
		#fwrite($file, date('Y-m-d H:i:s', time()) . "\t" . (isset($_POST['out_trade_no']) ? $_POST['out_trade_no'] : 'invalid visit') . "\n");
		#fclose($file);
		#log_file('wxpay_response: ' . json_encode($_REQUEST));

		$wxpay_obj = new WXPayModel();
		$success = $wxpay_obj->pay_response();
		if ($success)
		{
			echo 'success';
		}
	}

	/**
	 * 微信APP支付付款成功后的异步回调处理
	 * @author zt
	 * @param void
	 * @return void
	 * @todo 调用微信支付模型验证来源可靠性后，获取订单号，调用订单模型的payOrder方法设置订单状态为已付款
	 */
	public function wxpay_app_response()
	{
		$wxpay_obj = new WXPayModel();
		//$wxpay_obj->is_app = true;
		$success = $wxpay_obj->pay_response();
		if ($success)
		{
			echo 'success';
		}
	}
	

	//js弹窗函数
	protected function alert($msg, $redirect = '')
	{
		echo '<script>alert("' . $msg . '");</script>';
		
		if ($redirect)
		{
			echo '<script>location.href="' . $redirect . '"</script>';
			
		}
		else
		{
			echo '<script>location.href="' . url_jiemi($this->cur_url) . '"</script>'; 
			
		}
		exit;
	}

	/**
	 * 图片上传处理
	 * @author 姜伟
	 * @return string 返回JSON字符串
	 * @todo 调用upImageHandler函数处理上传图片
	 *
	 */
	public function uploadHandler()
	{
		$user_id = intval(session('user_id'));
		upImageHandler($_FILES['upfile'], '/user_file/' . $user_id);
	}

	//文件上传
	public function uploadFileHandler()
	{
		$user_id = intval(session('user_id'));
		upFileHandler($_FILES['upfile'], '/user/' . $user_id);
	}


	//点赞
	public function praise(){
		$user_id = session('user_id');
		$id = I('id', 0, 'intval');
		$type = I('type', 0, 'intval');
		$praise_type = I('praise_type');
		if($praise_type == 'post'){
			$praise_type = PraiseModel::POST;
		}elseif($praise_type == 'comment'){
			$praise_type = PraiseModel::COMMENT;
		}else{
			$praise_type = 0;
		}
		if(!$id || !$praise_type){
			$this->ajaxReturn(array('code'=>1, 'msg'=>'点赞失败'));
		}
		$praise_obj = new PraiseModel();
		if($type == 1){
			$user_obj = new UserModel($user_id);
			$user = $user_obj->getUserInfo('nickname');
			$data = array(
				'user_id' => $user_id,
				// 'nickname' => $user['nickname'],
				'praise_type' => $praise_type,
				'id' => $id,
				);
            if($praise_obj->addPraise($data)){
				$this->ajaxReturn(array('code'=>0, 'msg'=>'点赞成功'));
			}else{
				$this->ajaxReturn(array('code'=>1, 'msg'=>'点赞失败'));
			}
		}else{
			if($praise_obj->delPraise($user_id,$id)){
				$this->ajaxReturn(array('code'=>0, 'msg'=>'取消点赞'));
			}else{
				$this->ajaxReturn(array('code'=>1, 'msg'=>'取消点赞失败'));
			}
		}

	}


    //收藏
    public function collect(){

        $user_id = session('user_id');
        $post_id = I('id', 0, 'intval');
        $type = I('type', 0, 'intval');
        if(!$post_id){
            $this->ajaxReturn(array('code'=>1, 'msg'=>'收藏失败'));
        }

        $collect_obj = new CollectModel();
        if($type == 1){
            $data = array(
                'user_id' => $user_id,
                'post_id' => $post_id,
            );
            if($collect_obj->addCollect($data)){
                $this->ajaxReturn(array('code'=>0, 'msg'=>'爱你哟'));
            }else{
                $this->ajaxReturn(array('code'=>1, 'msg'=>'收藏失败'));
            }
        }else{
            if($collect_obj->delCollect($user_id,$post_id)){
                $this->ajaxReturn(array('code'=>0, 'msg'=>'哼，嫌弃你'));
            }else{
                $this->ajaxReturn(array('code'=>1, 'msg'=>'取消收藏失败'));
            }
        }

    }



    public function add_search(){

        $search_name = $this->_request('search_name');
        $user_id = intval(session('user_id'));
        if($search_name && $user_id){
            $search_obj = new SearchHistoryModel();
            $data=[
                'search_value'=>$search_name,
                'user_id'=>$user_id
            ];
            $search_obj->addSearchHistory($data);
        }
    }


    //关注频道
    public function follow_channel(){
        if(IS_AJAX && IS_POST){
            $user_id = intval(session('user_id'));
            $channel_id = I('channel_id', 0, 'intval');
            if(!$user_id) $this->ajaxReturn(array('code'=> 1, 'msg' => '请先登录'));
            if(!$channel_id) $this->ajaxReturn(array('code'=> 1, 'msg' => '系统出错，请稍后再试'));
            if(D('Follow')->setFollow($user_id, $channel_id, 1)){
            	$user_rank = D('UserChannelRank')->getUserChannelRankInfo('user_id ='.$user_id. ' and channel_id ='.$channel_id);
				$rank = D('ChannelRank')->getChannelRankInfo('channel_rank_id ='.$user_rank['channel_rank_id']);
                $this->ajaxReturn(array('code'=>0, 'msg'=>'操作成功', 'rank'=>$rank['rank_name']));
            }
            $this->ajaxReturn(array('code'=> 1, 'msg' => '系统出错，请稍后再试'));
        }
    }

    //关注用户
    public function follow_user(){
        if(IS_AJAX && IS_POST){
            $user_id = intval(session('user_id'));
            $by_user_id = I('user_id', 0, 'intval');
            if(!$user_id) $this->ajaxReturn(array('code'=> 1, 'msg' => '请先登录'));
            if(!$by_user_id) $this->ajaxReturn(array('code'=> 1, 'msg' => '系统出错，请稍后再试'));

            if(D('Follow')->setFollow($user_id, $by_user_id, 2)){
                $this->ajaxReturn(array('code'=>0, 'msg'=>'操作成功'));
            }
            $this->ajaxReturn(array('code'=> 1, 'msg' => '系统出错，请稍后再试'));
        }
    }


    function check_login(){

    	if(session('user_id')){
    		$user = M('Users')->where('user_id ='.session('user_id'))->find();
    		if($user['nickname'] && $user['sex'] && $user['headimgurl']){
    			$this->ajaxReturn(1);
    		}
    		
    	}
    }


    function check_post(){
    	if(IS_AJAX && IS_POST){
    		$user_id = intval(session('user_id'));
    		$channel_id = I('channel_id', 0,'intval');
    		$is_follow = D('Follow')->checkFollowChannel($user_id, $channel_id);
            if(!$is_follow) $this->ajaxReturn(array('code'=>0, 'msg'=>'请先关注频道'));

            $post_priv = D('ChannelTitlePriv')->checkPostPriv($user_id, $channel_id);
            if(!$post_priv) $this->ajaxReturn(array('code'=>0, 'msg'=>'您还没有发帖权限'));

            $this->ajaxReturn(array('code'=>1));
    	}
    }


    function get_no_read(){
    	$user_id = intval(session('user_id'));
    	$message_obj = new MessageModel();
    	//回复我的
        $reply_me_num = $message_obj->getMessageNum('reply_user_id ='.$user_id . ' and message_type ='.MessageModel::REPLY .' and is_read = 0');
        // echo $message_obj->getLastSql();
        //@我的
        $at_me_num = $message_obj->getMessageNum('reply_user_id ='.$user_id . ' and message_type ='.MessageModel::AT .' and is_read = 0');

        //system
        $sys_num = $message_obj->getMessageNum('reply_user_id ='.$user_id . ' and message_type in(4,5,6,7,8) and is_read = 0');
        // echo $message_obj->getLastSql();
        $this->ajaxReturn(array('reply_num'=>$reply_me_num, 'at_num'=>$at_me_num, 'sys_num'=>$sys_num));
    }
}

